import React from "react";
import { useState, useEffect } from "react";

export default function ChatRoom() {
    const serverUrl = 'http://localhost:1234';
    const [roomId, setRoomId] = useState('general');
    const [show, setShow] = useState(false);

    function handleChange(event) {
        console.log('update state, roomId:', event.target.value);
        // 更新roomId
        setRoomId(event.target.value);
    }

    return (
        <>
            <label style={{ display: 'flex', alignItems: 'center' }}>
                Choose the chat room: 
                <select value={roomId} onChange={handleChange} style={{ fontSize: '25px', marginLeft: '10px' }}>
                    <option value='general'>general</option>
                    <option value='travel'>travel</option>
                    <option value='food'>food</option>
                </select>

                <button onClick={() => setShow(!show)} style={{ fontSize: '25px', marginLeft: '10px' }}>
                    {show ? '关闭聊天' : '开始聊天'}
                </button>
            </label>
            {show && <br/>}
            {show && <Room serverUrl={serverUrl} roomId={roomId}/>}
        </>
    );
}

const Room = ({serverUrl, roomId}) => {

    useEffect(
        () => {
            console.log('serverUrl or roomId changed, execute useEffect.');
            const connection = createConnection(serverUrl, roomId);
            connection.connect();
            // 返回一个组件卸载时执行的方法, 用于清理, 类似componentWillUnmount
            return () => {
                console.log('clean up', roomId);
                connection.disconnect();
            };
        },
        [serverUrl, roomId]
    );

    return (
        <>
            <h2>welcom to {roomId} chat room.</h2>
        </>
    );
}

// 模拟创建连接, 连接到指定房间，返回连接对象
function createConnection(serverUrl, roomId) {
    console.log('create connection:', serverUrl, roomId);
    return {
        connect() {
            console.log('connect to server:', serverUrl, roomId);
        },
        disconnect() {
            console.log('disconnect from server:', serverUrl, roomId);
        }
    };
}
